import axios from 'axios'
import Message from '~/utils/messageUtil'

// 创建新的axios实例
const service = axios.create({
  baseURL: '/ic-openapi',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8' 
  // 判断localStorage是否存在token
  if (localStorage.getItem('token')) {
      config.headers.token= localStorage.getItem('token'); 
  }
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  refreshToken(response.headers)
  const data = response.data
  if (data.code === '200') {
    return data.data === undefined ? {} : data.data
  } else {
    // 0000 为自定义消息状态
    if(data.code === '0000' && data.msg) {
      Message('error', data.msg)
    } else {
      errorMsg(data.code)
    }
    // return Promise.resolve(data.data)
    throw new Error(data)
  }
}, error => {
  if (error && error.response) {
    const statusCode = error.response.status
    errorMsg(statusCode)
  }
  throw new Error(error)
})

/**
 * 刷新token
 * @param headers 
 * @returns 
 */
function refreshToken(headers: any) {
  if(!headers.token) {
    return
  }
  localStorage.setItem("token", headers.token)
}

/**
 * 错误统一处理方法
 * @param statusCode 
 */
function errorMsg(statusCode:string) {
  let errorMsg = msg[statusCode] || '服务正在部署，请稍后再试'
  Message('error', errorMsg)
}

/**
 * 错误类型
 */
interface MessageInterface {
  [key: string]: string;
}
const msg: MessageInterface = {
  "400": "请求发送失败，请检查网络",
  "401": "登录失效，请重新登录",
  "403": "暂无权限，请联系管理员",
  "408": "请求超时，请检查网络",
  "500": "服务异常，请联系管理员",
  "504": "网关超时,请联系管理员",
  "502": "服务正在部署，请稍后再试",
  "601": "您的账号已被禁用",
};

export default service